package com.tiance.web.controller.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tiance.constants.CommonConstants;
import com.tiance.dal.dataobject.MemberDO;
import com.tiance.domainservice.checker.BaseChecker;
import com.tiance.domainservice.checker.MemberParamsChecker;
import com.tiance.domainservice.domain.MemberDomain;
import com.tiance.enums.FileTypeEnum;
import com.tiance.enums.ImageTypeEnum;
import com.tiance.enums.OperateTypeEnum;
import com.tiance.exception.BusinessException;
import com.tiance.integration.cache.MapCacheUtil;
import com.tiance.integration.config.CommonProperties;
import com.tiance.utils.BeanConverterUtil;
import com.tiance.vo.MemberVO;
import com.tiance.vo.UploadVO;
import com.tiance.web.aspect.OperatorControllerLog;
import com.tiance.web.controller.base.BaseController;
import com.tiance.web.convertor.ModelConvert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/2/18
 *
 * Description：
 *
 * Modification History:
 *
 */
@Controller
@RequestMapping(value = "/common")
public class UploadController extends BaseController{
    private static String LOG_PREFIX ="MemberController| 公共控制器===>";
    @Autowired
    private CommonProperties commonProperties;

    @RequestMapping(value = "/toUpload.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到积分/信用页面")
    public String toUpload() {
        return "/front/test/upload.html";

    }

    @RequestMapping(value = "/uploadMemberImage.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="上传文件")
    public BaseResponse uploadMemberImage(HttpServletRequest request,@RequestParam("file")MultipartFile file, UploadVO uploadVO) throws
                                                                                                               IOException {
        BaseResponse<UploadVO> response=new BaseResponse<>();
        logger.info("开始上传文件，请求参数:{}");
        try {

            HttpSession session = request.getSession();
            Object memberId=session.getAttribute(CommonConstants.MEMBER_ID);
            if(null==memberId){
                throw new BusinessException("未获取到会员信息");
            }
            uploadVO.setMemberId((Long)memberId);

            this.checkFile(file);
            String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            logger.info("上传文件-获取到文件名后缀: "+fileSuffix + "，文件全名："+file.getOriginalFilename());
            File targetFile;
            //获取文件名加后缀
            String fileName=file.getOriginalFilename();
            if(fileName!=null&&fileName!="") {
                //文件存储位置
                String path = commonProperties.getUploadFilePath() +commonProperties.getUploadImagePrefixPath() + File.separator + uploadVO.getMemberId();
                //文件后缀
                String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                //新的文件名
                fileName = System.currentTimeMillis() + "_" + new Random().nextInt(1000) + fileF;

                //先判断文件是否存在

                //获取文件夹路径
                File file1 = new File(path);
                //如果文件夹不存在则创建
                if (!file1.exists() && !file1.isDirectory()) {
                    file1.mkdir();
                }
                //将图片存入文件夹
                targetFile = new File(file1, fileName);
                //将上传的文件写到服务器上指定的文件。
                file.transferTo(targetFile);

                String url=commonProperties.getUploadImagePrefixPath() +"/"+ uploadVO.getMemberId()+"/"+fileName;
                uploadVO.setUrl(url);
                response.setSuccess(true);
                response.setMessage("上传成功!");
                response.setResult(uploadVO);
            }

        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"上传文件失败，失败原因：",e1);
            response.setSuccess(false);
            response.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"上传文件失败,失败原因",e2);
            response.setSuccess(false);
            response.setMessage("上传文件失败");
        }
        logger.info("结束上传文件，返回数据:{}", JSON.toJSONString(response));
        return  response;

    }

    private void checkFile(MultipartFile file) {
        if (null==file) {
            throw new BusinessException("请选择需要上传的文件!");
        }

        if (file.isEmpty()) {
            throw new BusinessException("请选择需要上传的文件!");
        }
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") );
        if(!(ImageTypeEnum.GIF.getSuffix().equals(fileSuffix)
             ||ImageTypeEnum.JPEG.getSuffix().equals(fileSuffix)
               ||ImageTypeEnum.JPG.getSuffix().equals(fileSuffix)
        ||ImageTypeEnum.PNG.getSuffix().equals(fileSuffix))){
            throw new BusinessException("文件格式非法，请上传图片文件!");
        }

    }




}
